package com.yxzz.service;

import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginWxUser;
import com.yxzz.core.domain.PPatient;
import com.yxzz.core.domain.TUserPatientRela;
import com.yxzz.core.service.IPPatientService;
import com.yxzz.core.service.ITUserPatientRelaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserPatientRelationshipService {


    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private ITUserPatientRelaService tUserPatientRelaService;

    @Autowired
    private IPPatientService pPatientService;

    public List<PPatient> getPatientByUserId(LoginWxUser loginWxUser){
        Long[] ids = getPatientIds(loginWxUser);
        List<PPatient> list = pPatientService.selectPPatientListByIds(ids);
        return list;
    }

    public Long[] getPatientIds(LoginWxUser loginWxUser){
        Long[] ids = loginWxUser.getPatientIds().stream().toArray(Long[]::new);
        return ids;
    }

    public void addPatient(PPatient pPatient, LoginWxUser loginWxUser){
        pPatientService.insertPPatient(pPatient);
        if (pPatient.getId() == null){
            List<PPatient> tmpResult = pPatientService.selectPPatientList(pPatient);
            pPatient = tmpResult.get(0);
        }
        TUserPatientRela tUserPatientRela = new TUserPatientRela();
        tUserPatientRela.setUserId(loginWxUser.gettUser().getUserId());
        tUserPatientRela.setOpenId(loginWxUser.gettUser().getOpenId());
        tUserPatientRela.setPatientId(pPatient.getId());
        tUserPatientRelaService.insertTUserPatientRela(tUserPatientRela);
        loginWxUser.getPatientIds().add(pPatient.getId());
        tokenService.setLoginUser(loginWxUser);
    }
}
